//
//  FDMFindViewController.m
//  FDM_Entertainment Circle
//
//  Created by dllo on 16/4/18.
//  Copyright © 2016年 付冬梅. All rights reserved.
//

#import "FDMFindViewController.h"
#import "FDMFindTitleCollectionViewCell.h"
#import "FDMFindSectionOneCollectionViewCell.h"
#import "FDMPushWheelImages.h"
#import "FDMFindBigCollectionViewCell.h"
#import "FDMKindCollectionViewCell.h"
#import "FDMBroadcastCollectionViewCell.h"
#import "FDMTopRadioCollectionViewCell.h"
#import "FDMMasterCollectionViewCell.h"
#import "FDMMasterDetailViewController.h"
#import "FDMSearchBarViewController.h"

@interface FDMFindViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, FDMMasterCollectionViewDelegate, UIScrollViewDelegate>

@property (nonatomic, retain) FDMBaseCollectionView *collectionView;/**< 大的滚动视图 */

@property (nonatomic, retain) FDMBaseCollectionView *titleCollectionView;/**< 标题滚动视图 */

@property (nonatomic, retain) NSMutableArray *titleArray;/**< 标题数组 */

//@property (nonatomic, retain) NSMutableArray *dataSourceModelArray;/**< 数据源Model数组 */

@property (nonatomic, retain) UIView *greenView;

@property (nonatomic, assign) NSInteger currentRows;

@property (nonatomic, retain) NSIndexPath *index;

@end

@implementation FDMFindViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    self.navigationController.automaticallyAdjustsScrollViewInsets = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.navigationController.navigationBar.translucent = NO;
    
    // 创建左右标题
    [self createLeftAndRightItem];
    
    // 创建集合视图
    [self createCollectionView];
    [self createBigCollectionView];
    
    // 数据处理
    [self dataHandel];
    
    // 创建绿色滚动条
    [self createGreenView];
    
    // 初始化
    self.titleArray = [NSMutableArray array];
    
    // 创建一个indexpath
    NSIndexPath *indexpath = [NSIndexPath indexPathForRow:0 inSection:0];
    self.currentRows = 0;
}

#pragma mark - 创建左右标题
- (void)createLeftAndRightItem {
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"喜马拉雅FM" style:UIBarButtonItemStylePlain target:self action:@selector(leftItemAction:)];
    self.navigationItem.leftBarButtonItem = leftItem;
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor redColor];
    [leftItem release];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(rightItemAction:)];
    self.navigationItem.rightBarButtonItem = rightItem;
    [rightItem release];
}

- (void)leftItemAction:(UIBarButtonItem *)leftItem {
    
}

- (void)rightItemAction:(UIBarButtonItem *)rightItem {
    FDMSearchBarViewController *searchController = [[FDMSearchBarViewController alloc] init];
    [self.navigationController pushViewController:searchController animated:YES];
    [searchController release];
}

#pragma mark - 创建集合视图
- (void)createCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    layout.sectionInset = UIEdgeInsetsMake(10, 0, 10, 0);
    
    self.titleCollectionView = [[FDMBaseCollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40) collectionViewLayout:layout];
    self.titleCollectionView.delegate = self;
    self.titleCollectionView.dataSource = self;
    [self.view addSubview:self.titleCollectionView];
    self.titleCollectionView.backgroundColor = [UIColor whiteColor];
    self.titleCollectionView.bounces = NO;
    self.titleCollectionView.showsHorizontalScrollIndicator = NO;
    [self.titleCollectionView release];
    [self.titleCollectionView registerClass:[FDMFindTitleCollectionViewCell class] forCellWithReuseIdentifier:@"FDMFindTitleCollectionViewCell"];
}

- (void)createBigCollectionView {
    // 大的集合视图
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionView = [[FDMBaseCollectionView alloc] initWithFrame:CGRectMake(0, 50, SCREEN_WIDTH, SCREEN_HEIGHT - 157 - self.greenView.frame.size.height) collectionViewLayout:flowLayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.pagingEnabled = YES;
    [self.view addSubview:self.collectionView];
    
    [self addObserver];
    // 注册
    // 推荐
    [self.collectionView registerClass:[FDMFindBigCollectionViewCell class] forCellWithReuseIdentifier:@"FDMFindBigCollectionViewCell"];
    // 分类
    [self.collectionView registerClass:[FDMKindCollectionViewCell class] forCellWithReuseIdentifier:@"FDMKindCollectionViewCell"];
    // 广播
    [self.collectionView registerClass:[FDMBroadcastCollectionViewCell class] forCellWithReuseIdentifier:@"FDMBroadcastCollectionViewCell"];
    // 榜单
    [self.collectionView registerClass:[FDMTopRadioCollectionViewCell class] forCellWithReuseIdentifier:@"FDMTopRadioCollectionViewCell"];
    // 主播
    [self.collectionView registerClass:[FDMMasterCollectionViewCell class] forCellWithReuseIdentifier:@"FDMMasterCollectionViewCell"];
}

/** 视图即将出现时显示导航栏 */
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

#pragma mark - 添加观察者
- (void)addObserver {
    [self.collectionView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:@"ddd"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    CGFloat x = [[change objectForKey:@"new"] CGPointValue].x;
    CGFloat newX = x * SCREEN_WIDTH / self.titleArray.count / SCREEN_WIDTH;
    // 修改绿色滚动条的位置
    self.greenView.transform = CGAffineTransformMakeTranslation(newX, 0);
}

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    CGFloat collectionViewX = self.collectionView.contentOffset.x;
//    CGFloat greenX = collectionViewX / self.titleArray.count;
//    self.greenView.transform = CGAffineTransformMakeTranslation(greenX, 0);
//}

#pragma mark - 创建绿色滚动条
- (void)createGreenView {
    
    // 绿色滚动条
    self.greenView = [[UIView alloc] init ];
    self.greenView.backgroundColor = [UIColor greenColor];
    [self.view addSubview:_greenView];
    [self.greenView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleCollectionView.mas_bottom);
        make.left.equalTo(self.view.mas_left);
        make.height.equalTo(@4);
        make.width.equalTo(@((SCREEN_WIDTH) / 5));
    }];
    
    self.greenView.layer.cornerRadius = 2;
    self.greenView.layer.masksToBounds = YES;
    [_greenView release];
}

#pragma mark - collectionView代理方法
// cell大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.titleCollectionView) {
        return CGSizeMake((SCREEN_WIDTH - 24)/ self.titleArray.count, 20);
    }
    if (collectionView == self.collectionView) {
        return CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT - 157);
    }
    return CGSizeZero;
    
}

// cell个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == self.titleCollectionView) {
        return self.titleArray.count;
    }
    if (collectionView == self.collectionView) {
        return self.titleArray.count;
    }
    return 0;
    
}

// cell赋值
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.titleCollectionView) {
        
        FDMFindTitleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FDMFindTitleCollectionViewCell" forIndexPath:indexPath];
        cell.titleLabel.text = self.titleArray[indexPath.row][@"title"];
        if (indexPath.row == self.currentRows) {
            cell.titleLabel.textColor = [UIColor redColor];
        } else {
            cell.titleLabel.textColor = [UIColor blackColor];
        }
        
        return cell;
    }
    if (collectionView == self.collectionView) {
        if (indexPath.row == 0) {
            FDMFindBigCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FDMFindBigCollectionViewCell" forIndexPath:indexPath];
            return cell;
        }
        if (indexPath.row == 1) {
            FDMKindCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FDMKindCollectionViewCell" forIndexPath:indexPath];
            return cell;
        }
        if (indexPath.row == 2) {
            FDMBroadcastCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FDMBroadcastCollectionViewCell" forIndexPath:indexPath];
            return cell;
        }
        if (indexPath.row == 3) {
            FDMTopRadioCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FDMTopRadioCollectionViewCell" forIndexPath:indexPath];
            
            return cell;
        } else {
            FDMMasterCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FDMMasterCollectionViewCell" forIndexPath:indexPath];
            /** 设置代理人 */
            cell.jumpDelegate = self;
            return cell;
        }
        
    }
    return nil;
    
}

#pragma mark - 在拖拽减速执行中设置titleCollectionView的效果
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.collectionView) {
        // titleCollectionView变为红色
        NSInteger cellNumber = self.collectionView.contentOffset.x / SCREEN_WIDTH;
        FDMFindTitleCollectionViewCell *currentTitleCell = (FDMFindTitleCollectionViewCell *)[self.titleCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:cellNumber inSection:0]];
        currentTitleCell.titleLabel.textColor = [UIColor redColor];
//        NSLog(@"%ld", cellNumber);
        // titleCollecitonView变为黑色
        if (cellNumber != self.currentRows) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.currentRows inSection:0];
            FDMFindTitleCollectionViewCell *pastCell = (FDMFindTitleCollectionViewCell *)[self.titleCollectionView cellForItemAtIndexPath:indexPath];
            pastCell.titleLabel.textColor = [UIColor blackColor];
        }
        
//        NSLog(@"%ld", self.currentRows);
        self.currentRows = cellNumber;
        [UIView animateWithDuration:1 animations:^{
            self.greenView.frame = CGRectMake(cellNumber * SCREEN_WIDTH / self.titleArray.count, 40, SCREEN_WIDTH / self.titleArray.count, 4);
        }];
        
        FDMFindTitleCollectionViewCell *selectedCell = (FDMFindTitleCollectionViewCell *)[self.titleCollectionView cellForItemAtIndexPath:self.index];
        selectedCell.titleLabel.textColor = [UIColor blackColor];
        
    }
}

// cell点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    self.index = indexPath;
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
    FDMFindTitleCollectionViewCell *cellOfZero = (FDMFindTitleCollectionViewCell *)[collectionView cellForItemAtIndexPath:index];
    cellOfZero.titleLabel.textColor = [UIColor blackColor];
    FDMFindTitleCollectionViewCell *cell = (FDMFindTitleCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.titleLabel.textColor = [UIColor redColor];
    [self.collectionView setContentOffset:CGPointMake(SCREEN_WIDTH * indexPath.row, 0) animated:YES];
//    [UIView animateWithDuration:1 animations:^{
//        self.greenView.frame = CGRectMake(indexPath.row * SCREEN_WIDTH / self.titleArray.count, 40, SCREEN_WIDTH / self.titleArray.count, 4);
//    }];
}

// cell取消选择方法
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    FDMFindTitleCollectionViewCell *cell = (FDMFindTitleCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.titleLabel.textColor = [UIColor blackColor];
}

#pragma mark - 数据处理
- (void)dataHandel {
    
    // 标题数据
    NSString *titleStr = @"http://mobile.ximalaya.com/mobile/discovery/v1/tabs?device=android";
    [APPTools GETWithURL:titleStr par:nil success:^(id responseObject) {
        self.titleArray = responseObject[@"tabs"][@"list"];
        
        [self.titleCollectionView reloadData];
        [self.collectionView reloadData];
    } failed:^(NSError *error) {
        NSLog(@"%@", error);
    }];
    
}

#pragma mark - 实现主播页跳转协议方法
- (void)clickCellToNextControllerWithUserId:(NSString *)userId {
    FDMMasterDetailViewController *masterController = [[FDMMasterDetailViewController alloc] init];
    masterController.uid = userId;
    [self.navigationController pushViewController:masterController animated:YES];
    [masterController release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
